package com.xywy.bloodandroid.fragment;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.xywy.bloodandroid.R;
import com.xywy.bloodandroid.act.BPNewsActivity;
import com.xywy.bloodandroid.act.BloodDetailAct;
import com.xywy.bloodandroid.act.DataRecordActivity;
import com.xywy.bloodandroid.act.QuestionListAct;
import com.xywy.bloodandroid.act.RemindListActivity;
import com.xywy.bloodandroid.base.BaseFragment;
import com.xywy.bloodandroid.bean.BloodPressureData;
import com.xywy.bloodandroid.bean.BloodPresureDataFromServer;
import com.xywy.bloodandroid.bean.User;
import com.xywy.bloodandroid.dao.BaseDao;
import com.xywy.bloodandroid.dao.BloodPressureDataDao;
import com.xywy.bloodandroid.dao.BloodPressureDataDao.Properties;
import com.xywy.bloodandroid.util.DevicesObserver;
import com.xywy.bloodandroid.util.MD5;
import com.xywy.bloodandroid.util.ObserverConstants;
import com.xywy.bloodandroid.util.UIUtil;
import com.xywy.bloodandroid.vollery.GetRequest;
import com.xywy.bloodandroid.vollery.OnVolleyResponseListener;
import com.xywy.bloodandroid.vollery.PostRequest;
import com.xywy.bloodandroid.vollery.VolleyManager;
import com.xywy.bloodandroid.widget.BloodZxView;

import de.greenrobot.dao.query.QueryBuilder;

/**
 * *****************************************
 * 
 * @Title: BloodFragment.java
 * @Package com.xywy.bloodandroid.fragment
 * @Description: TODO(血压管理)
 * @author smz
 * @date 2014-12-23 下午2:01:07
 * @version V1.0
 ******************************************* 
 */
public class BloodFragment extends BaseFragment implements OnClickListener {
	private RelativeLayout left_img;
	private TextView middle_title;
	private ImageView iv_upload_bp_data;
	private TextView tv_ask_doctor;
	private TextView tv_news;
	private TextView tv_remind;
	private BloodPressureDataDao bloodDao;
	private BloodZxView blood_pressure_chart;
	private TextView btn_hr_detail_day, btn_hr_detail_week,
			btn_hr_detail_month, btn_hr_detail_year;
	SharedPreferences sp;

	String userid = null;
	private Editor editor;
	private TextView tv_last_day;

	public static final String SECRETKEY_WEIGHT_SCALEF = "213aBc$l;@13";
	// public static final String SECRETKEY_BLOOD_PRESURE = "2CV3aBc$l;@";
	public static final String TAG = "ISyncBleDevice";
	int current = BloodZxView.MODE_DAY;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_blood_pressure, null);
		sp = getActivity().getSharedPreferences("config", Context.MODE_PRIVATE);
		editor = sp.edit();
		userid = User.getInstance(getActivity()).getUserid();
		initView(view);
		registerDBobserver();
		initDAO();
		initListener();
		initdata();
		if (userid != null && !"".equals(userid)) {
			setChange();
		}
		return view;
	}

	private void initView(View view) {
		left_img = (RelativeLayout) view.findViewById(R.id.left_img);
		left_img.setVisibility(View.GONE);
		middle_title = (TextView) view.findViewById(R.id.middle_title);
		middle_title.setText(R.string.bp_manage);
		iv_upload_bp_data = (ImageView) view
				.findViewById(R.id.iv_upload_bp_data);
		tv_ask_doctor = (TextView) view.findViewById(R.id.tv_ask_doctor);
		tv_news = (TextView) view.findViewById(R.id.tv_news);
		tv_remind = (TextView) view.findViewById(R.id.tv_remind);

		btn_hr_detail_day = (TextView) view
				.findViewById(R.id.btn_bp_detail_day);
		btn_hr_detail_week = (TextView) view
				.findViewById(R.id.btn_bp_detail_week);
		btn_hr_detail_month = (TextView) view
				.findViewById(R.id.btn_bp_detail_month);
		btn_hr_detail_year = (TextView) view
				.findViewById(R.id.btn_bp_detail_year);

		btn_hr_detail_day.setOnClickListener(this);
		btn_hr_detail_week.setOnClickListener(this);
		btn_hr_detail_month.setOnClickListener(this);
		btn_hr_detail_year.setOnClickListener(this);
		blood_pressure_chart = (BloodZxView) view
				.findViewById(R.id.blood_pressure_chart);
		tv_last_day = (TextView) view.findViewById(R.id.tv_last_day);
		blood_pressure_chart.setOnClickListener(this);
	}

	private void initListener() {
		iv_upload_bp_data.setOnClickListener(this);
		tv_ask_doctor.setOnClickListener(this);
		tv_news.setOnClickListener(this);
		tv_remind.setOnClickListener(this);
	}

	private void initdata() {
		syncDataFormServer();
		System.out.println(getYearAgoData().length);
		blood_pressure_chart
				.setGaveWorth(getDayAgoData(), BloodZxView.MODE_DAY);
		setSelectHr(BloodZxView.MODE_DAY);
	}

	@Override
	public void onClick(View view) {
		// TODO Auto-generated method stub
		switch (view.getId()) {
		case R.id.iv_upload_bp_data:// 上传数据
			startActivity(new Intent(getActivity(), DataRecordActivity.class));
			break;
		case R.id.tv_ask_doctor:// 问医生
			Intent ask_intent = new Intent(getActivity(), QuestionListAct.class);
			getActivity().startActivity(ask_intent);
			// startActivity(new Intent(getActivity(),
			// DataRecordActivity.class));
			break;
		case R.id.tv_news:// 资讯
			startActivity(new Intent(getActivity(), BPNewsActivity.class));
			break;
		case R.id.tv_remind:// 提醒
			startActivity(new Intent(getActivity(), RemindListActivity.class));
			break;
		case R.id.btn_bp_detail_day:
			blood_pressure_chart.setGaveWorth(getDayAgoData(),
					BloodZxView.MODE_DAY);
			setSelectHr(BloodZxView.MODE_DAY);
			break;
		case R.id.btn_bp_detail_week:
			blood_pressure_chart.setGaveWorth(getWeekAgoData(),
					BloodZxView.MODE_WEEK);
			setSelectHr(BloodZxView.MODE_WEEK);
			break;
		case R.id.btn_bp_detail_month:
			blood_pressure_chart.setGaveWorth(getMonthAgoData(),
					BloodZxView.MODE_MOUNTH);
			setSelectHr(BloodZxView.MODE_MOUNTH);
			break;
		case R.id.btn_bp_detail_year:
			blood_pressure_chart.setGaveWorth(getYearAgoData(),
					BloodZxView.MODE_YEAR);
			setSelectHr(BloodZxView.MODE_YEAR);
			break;
		case R.id.blood_pressure_chart:
			Intent intent = new Intent(getActivity(), BloodDetailAct.class);
			startActivity(intent);
			break;

		default:
			break;
		}

	}

	private void initDAO() {
		BaseDao baseDao = BaseDao.getInstance(getActivity());
		bloodDao = baseDao.getBloodPressureDataDao();
	}

	/**
	 * 获得一天的数据
	 * 
	 * @return
	 */
	private BloodPressureData[] getDayAgoData() {
		BloodPressureData[] blood;
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.SECOND, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.MILLISECOND, 0);
		Date date = cal.getTime();
		QueryBuilder<BloodPressureData> qb = bloodDao.queryBuilder();
		qb.orderAsc(Properties.Date);
		qb.where(Properties.Date.gt(date.getTime()));
		List<BloodPressureData> datas = qb.list();
		for (BloodPressureData te : datas) {
			Log.e("datas --time -- weight", new Date(te.getDate()).toString()
					+ te.getHighPressure());
		}
		blood = new BloodPressureData[24];
		long weekDate = date.getTime();

		for (int i = 0; i < datas.size(); i++) {
			long curDate = datas.get(i).getDate();
			int temp = (int) (curDate - weekDate) / (1000 * 60 * 60);
			Log.e("temp---", temp + "");
			cal.setTimeInMillis(weekDate);
			Log.e("date", cal.get(Calendar.DATE) + "");
			Log.e("temp", temp + "");
			Log.e("iiiiii", i + "");
			if (temp < blood.length && temp >= 0)
				blood[temp] = datas.get(i);
		}
		return blood;
	}

	/**
	 * 获取一周以内的数据
	 * 
	 * @return
	 */
	private BloodPressureData[] getWeekAgoData() {

		BloodPressureData[] blood = new BloodPressureData[7];

		Calendar curr = Calendar.getInstance();
		curr.set(Calendar.DAY_OF_MONTH, curr.get(Calendar.DAY_OF_MONTH) - 7);
		Date date = curr.getTime();
		QueryBuilder<BloodPressureData> qb = bloodDao.queryBuilder();
		qb.where(Properties.Date.gt(date.getTime()));
		List<BloodPressureData> datas = qb.list();
		long weekDate = date.getTime();
		
		Calendar curr_calendar = Calendar.getInstance();
		int year_current = curr_calendar.get(Calendar.YEAR);
		int day_current = curr_calendar.get(Calendar.DAY_OF_YEAR);
		for (int i = 0; i < datas.size(); i++) {
			Calendar temp_calendar = Calendar.getInstance();
			temp_calendar.setTimeInMillis(datas.get(i).getDate());
			int year_temp = temp_calendar.get(Calendar.YEAR);
			int day_temp = temp_calendar.get(Calendar.DAY_OF_YEAR);
			
			int temp = -1;
//			long curDate = datas.get(i).getDate();
//			int temp = (int) ((curDate - weekDate) / 86400000);
			if(year_temp == year_current){
				temp = day_current - day_temp;
			}else {
				temp = day_current+31-day_temp;
			}
			if (temp >= 0 && temp < blood.length)
				blood[temp] = datas.get(i);
		}
		return blood;
	}

	/**
	 * 获取一个月以内的数据
	 * 
	 * @return
	 */
	private BloodPressureData[] getMonthAgoData() {
		BloodPressureData[] blood = new BloodPressureData[31];

		Calendar curr = Calendar.getInstance();

		curr.set(Calendar.MONTH, curr.get(Calendar.MONTH) - 1);
		Date date = curr.getTime();
		QueryBuilder<BloodPressureData> qb = bloodDao.queryBuilder();
		qb.where(Properties.Date.gt(date.getTime()));
		List<BloodPressureData> datas = qb.list();
		long weekDate = date.getTime();
		
		Calendar curr_calendar = Calendar.getInstance();
		int year_current = curr_calendar.get(Calendar.YEAR);
		int day_current = curr_calendar.get(Calendar.DAY_OF_YEAR);
		for (int i = 0; i < datas.size(); i++) {
			Calendar temp_calendar = Calendar.getInstance();
			temp_calendar.setTimeInMillis(datas.get(i).getDate());
			int year_temp = temp_calendar.get(Calendar.YEAR);
			int day_temp = temp_calendar.get(Calendar.DAY_OF_YEAR);
			
			int temp = -1;
//			long curDate = datas.get(i).getDate();
//			int temp = (int) ((curDate - weekDate) / 86400000);
			if(year_temp == year_current){
				temp = day_current - day_temp;
			}else {
				temp = day_current+31-day_temp;
			}
			if (temp >= 0 && temp < blood.length)
				blood[temp] = datas.get(i);
		}
		return blood;
	}

	/**
	 * 获取一年以内的数据
	 * 
	 * @return
	 */
	private BloodPressureData[] getYearAgoData() {
		BloodPressureData[] blood = new BloodPressureData[12];

		Calendar c = Calendar.getInstance();
		c.add(Calendar.YEAR, -1);
		Date date = c.getTime();
		QueryBuilder<BloodPressureData> qb = bloodDao.queryBuilder();
		qb.where(Properties.Date.gt(date.getTime()));
		List<BloodPressureData> datas = qb.list();
		long weekDate = date.getTime();

		for (int i = 0; i < datas.size(); i++) {
			long curDate = datas.get(i).getDate();
			int haha = (int) ((curDate - weekDate) / (86400 * 31));
			int temp = haha / 1000;
			if (temp >= 0 && temp < blood.length)
				blood[temp] = datas.get(i);
		}
		return blood;
	}

	/**
	 * 获取最后一条数据
	 * 
	 * @return
	 */
	private List<BloodPressureData> getLastData() {
		QueryBuilder<BloodPressureData> qb = bloodDao.queryBuilder();
		qb.orderDesc(Properties.Id);
		return qb.list();
	}

	private void setSelectHr(int index) {
		Drawable tab_button = getResources().getDrawable(R.drawable.tab_button);
		Drawable tab_button_white = getResources().getDrawable(
				R.drawable.tab_button_white);
		int white = getResources().getColor(R.color.white_color);
		int light_black = getResources().getColor(R.color.light_black);
		switch (index) {
		case BloodZxView.MODE_DAY:
			current = BloodZxView.MODE_DAY;
			btn_hr_detail_day.setTextColor(white);
			btn_hr_detail_week.setTextColor(light_black);
			btn_hr_detail_month.setTextColor(light_black);
			btn_hr_detail_year.setTextColor(light_black);
			btn_hr_detail_day.setBackgroundDrawable(tab_button);
			btn_hr_detail_week.setBackgroundDrawable(tab_button_white);
			btn_hr_detail_month.setBackgroundDrawable(tab_button_white);
			btn_hr_detail_year.setBackgroundDrawable(tab_button_white);
			break;
		case BloodZxView.MODE_MOUNTH:
			current = BloodZxView.MODE_MOUNTH;
			btn_hr_detail_day.setTextColor(light_black);
			btn_hr_detail_week.setTextColor(light_black);
			btn_hr_detail_month.setTextColor(white);
			btn_hr_detail_year.setTextColor(light_black);
			btn_hr_detail_day.setBackgroundDrawable(tab_button_white);
			btn_hr_detail_week.setBackgroundDrawable(tab_button_white);
			btn_hr_detail_month.setBackgroundDrawable(tab_button);
			btn_hr_detail_year.setBackgroundDrawable(tab_button_white);
			break;
		case BloodZxView.MODE_WEEK:
			current = BloodZxView.MODE_WEEK;
			btn_hr_detail_day.setTextColor(light_black);
			btn_hr_detail_week.setTextColor(white);
			btn_hr_detail_month.setTextColor(light_black);
			btn_hr_detail_year.setTextColor(light_black);
			btn_hr_detail_day.setBackgroundDrawable(tab_button_white);
			btn_hr_detail_week.setBackgroundDrawable(tab_button);
			btn_hr_detail_month.setBackgroundDrawable(tab_button_white);
			btn_hr_detail_year.setBackgroundDrawable(tab_button_white);
			break;
		case BloodZxView.MODE_YEAR:
			current = BloodZxView.MODE_YEAR;
			btn_hr_detail_day.setTextColor(light_black);
			btn_hr_detail_week.setTextColor(light_black);
			btn_hr_detail_month.setTextColor(light_black);
			btn_hr_detail_year.setTextColor(white);
			btn_hr_detail_day.setBackgroundDrawable(tab_button_white);
			btn_hr_detail_week.setBackgroundDrawable(tab_button_white);
			btn_hr_detail_month.setBackgroundDrawable(tab_button_white);
			btn_hr_detail_year.setBackgroundDrawable(tab_button);
			break;
		default:
			break;
		}
	}

	public void syncDataFormServer() {
		try {
			userid = User.getInstance(getActivity()).getUserid();
		} catch (Exception e) {
			// TODO: handle exception
		}

		if (userid == null || "".equals(userid)) {
			return;
		}
		long lastDownLoadTime = sp.getLong("last_download_blood_presure_time",
				1000); // 最后的下载时间；
		String device_id = "temp_automactily_device_identify";
		String appCount = "xywy_tizhong";
		String dataType = "xueya";
		// userid
		String time = (lastDownLoadTime / 1000) + "";
		String maxItem = "200";
		String curPage = "1";
		String sn = "";
		try {
			System.out.println("sn  之前----" + SECRETKEY_WEIGHT_SCALEF
					+ device_id + dataType + userid + time + maxItem + curPage
					+ appCount);
			System.out.println(SECRETKEY_WEIGHT_SCALEF);
			System.out.println("device_id " + device_id);
			System.out.println("dataType " + dataType);
			System.out.println("userid " + userid);
			System.out.println("time " + time);
			System.out.println("maxItem " + maxItem);
			System.out.println("curPage " + curPage);
			System.out.println("appCount " + appCount);
			sn = MD5.md5s(SECRETKEY_WEIGHT_SCALEF + device_id + dataType
					+ userid + time + maxItem + curPage + appCount);
			System.out.println(sn);
		} catch (Exception e) {
			e.printStackTrace();
		}
		String urlStr = "http://api.yun.xywy.com/index.php/api/getdata/data/"
				+ device_id + "/" + appCount + "/" + dataType + "/" + userid
				+ "/" + time + "/" + maxItem + "/" + curPage + "/" + sn + "/";
		GetRequest<String> request = new GetRequest<String>(urlStr,
				String.class, new OnVolleyResponseListener<String>() {

					@Override
					public void onError(VolleyError volleyError) {
						volleyError.printStackTrace();
						UIUtil.DissDialog(getActivity(), waittingDialog);
					}

					@Override
					public void onSuccess(String response) {
						UIUtil.DissDialog(getActivity(), waittingDialog);
						if (response != null) {
							System.out.println(response);
							parseJson(response);
						} else {
							Toast.makeText(getActivity(), "同步数据失败",
									Toast.LENGTH_SHORT).show();
						}
					}
				});
		request.setIsParseJson(false);
		VolleyManager.addRequest(request, "syncblooddata");
	}

	public void parseJson(String result) {
		List<BloodPresureDataFromServer> datas = new ArrayList<BloodPresureDataFromServer>();
		Log.d(TAG, "血压：解析从服务器上获取数据 ");
		try {
			JSONObject jsonObject = new JSONObject(result);
			int status = jsonObject.getInt("status");
			if (status == 0) { // 正确与服务器交互；
				JSONArray array = jsonObject.optJSONArray("data");
				for (int i = 0; i < array.length(); i++) {
					JSONObject item = (JSONObject) array.get(i);
					BloodPresureDataFromServer bs = new BloodPresureDataFromServer();
					bs.setXywy_userid(item.optString("xywy_userid"));
					bs.setApp_user_id(item.optString("app_user_id"));
					bs.setDatatime(Long.parseLong(item.optString("datatime")));
					bs.setHigh(Float.parseFloat(item.optString("high")));

					bs.setHigh(Float.parseFloat(item.optString("high")));
					bs.setLow(Float.parseFloat(item.optString("low")));
					bs.setHeart(Float.parseFloat(item.optString("heart")));
					bs.setApp_data(item.optString("app_data"));
					bs.setShou_data(item.optString("high"));
					datas.add(bs);

				}
				Log.d(TAG, "血压：成功获取数据 ");
				if (datas != null)
					dataCall(datas);
			} else {
				editor.putLong("last_download_blood_presure_time",
						System.currentTimeMillis()).commit();
			}
			// 这个时候 就该是上传的时间了吧
		} catch (JSONException e) {
			e.printStackTrace();
		}

	}

	public void dataCall(List<BloodPresureDataFromServer> lists) {

		// 3 当数据正常处理之后 ， 开始上传1中获取到的数据；
		if (lists == null || lists.size() < 1) {
			Log.d(TAG, "血压： 当前数据获取失败，或者解析异常， 导致同步体重数据库失败！");
			uploadDataToServer();
			return;
		}
		System.out.println("血压计从服务器同步并且插入");
		for (BloodPresureDataFromServer list : lists) {
			long date = (long) (list.getDatatime() * 1000); // *1000
															// 因为服务器上为ios
			if (!dataCanInsert(date)) {
				continue;
			}
			BloodPressureData data = new BloodPressureData(null,
					list.getHeart(), list.getHigh(), list.getLow(), "State",
					"temp_automactily_device_identify",
					"temp_handly_device_identify", date);
			bloodDao.insert(data);
		}
		// 将数据保存之后，获取最后一条的时间来替换本地数据；
		editor.putLong("last_download_blood_presure_time",
				(long) (lists.get(lists.size() - 1).getDatatime() * 1000))
				.commit();
//		uploadDataToServer();
		setChange();
	}

	/**
	 * 
	 * @return
	 */

	private boolean dataCanInsert(long time) {
		QueryBuilder<BloodPressureData> qb = bloodDao.queryBuilder();
		qb.where(Properties.Date.gt(time - 1000));
		qb.where(Properties.Date.gt(time + 1000));
		List<BloodPressureData> list = qb.list();
		if (list != null && list.size() > 0) {
			return false;
		}
		return true;
	}

	private final String sort = "xueya";
	private String URL_UPLOAD = "http://api.yun.xywy.com/index.php/api/setdata/data_all/";

	private void uploadDataToServer() {
		// data.setDate(data.getDate() / 1000);
		System.out.println("uploadDataToServer----");
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("app_username", "xywy_tizhong");
		try {
			String userid = User.getInstance(getActivity()).getUserid();
		} catch (Exception e) {
			// TODO: handle exception
		}

		if (userid == null || "".equals(userid)) {
			return;
		}
		params.put("xywy_userid", userid);
		params.put("sort", sort);
		// -------------------
		final List<BloodPressureData> pressuerDatas = getUnuploadData();
		String dataStr = turn2ServerJsonData(pressuerDatas, userid);
		params.put("data", dataStr);
		System.out.println("data---str----" + dataStr);
		params.put("datatime", System.currentTimeMillis() / 1000 + "");
		// -------------------
		String sn = BloodFragment.SECRETKEY_WEIGHT_SCALEF + userid + sort
				+ dataStr + "xywy_tizhong";
		try {
			params.put("sn", MD5.md5s(sn));
		} catch (Exception e) {
			e.printStackTrace();
		}

		PostRequest<String> post = new PostRequest<String>(URL_UPLOAD,
				String.class, new OnVolleyResponseListener<String>() {

					@Override
					public void onError(VolleyError volleyError) {
						volleyError.printStackTrace();
						UIUtil.DissDialog(getActivity(), waittingDialog);
					}

					@Override
					public void onSuccess(String response) {
						UIUtil.DissDialog(getActivity(), waittingDialog);
						if (response == null) {
							return;
						}
						try {
							JSONObject json = new JSONObject(response);
							int status = json.optInt("status");
							if (status == 0) {
								// bloodDao.insert(blood_data);
								// 将数据保存之后，获取最后一条的时间来替换本地数据；
								editor.putLong(
										"last_download_blood_presure_time",
										(long) (pressuerDatas.get(pressuerDatas
												.size() - 1).getDate()))
										.commit();
								// showToast("上传成功");
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
						System.out.println("------------" + response);
					}
				});
		post.setIsParseJson(false);
		post.setParams(params);
		System.out.println(params);
		executeRequest(post);
	}

	/**
	 * 获得需要上传的数据
	 * 
	 * @return
	 */
	public List<BloodPressureData> getUnuploadData() {
		long lastSaveTime = sp
				.getLong("last_download_blood_presure_time", 1000); // 最后的上传时间
		Log.e("time---", lastSaveTime + "");
		QueryBuilder<BloodPressureData> qb = bloodDao.queryBuilder();
		qb.orderAsc(Properties.Date).where(Properties.Date.gt(lastSaveTime));
		Log.e(TAG, "血压： 从本地获取需要上传的数据: " + qb.list().size());
		return qb.list();
	}

	/**
	 * 将数据库中提取出来的数据转换成服务器的been
	 * 
	 * @param data
	 */
	private String turn2ServerJsonData(List<BloodPressureData> datas,
			String userID) {
		Gson gson = new Gson();
		List<BloodPresureDataFromServer> bloodServers = new ArrayList<BloodPresureDataFromServer>();
		for (BloodPressureData data : datas) {
			BloodPresureDataFromServer dataFormServer = new BloodPresureDataFromServer();
			dataFormServer.setApp_data(data.getDevice_id());
			dataFormServer.setApp_user_id("");
			dataFormServer.setDatatime(data.getDate() / 1000);// 时间上面已经处理
			dataFormServer.setHeart(data.getHeartRate());
			dataFormServer.setHigh(data.getHighPressure());
			dataFormServer.setLow(data.getLowPressure());
			dataFormServer.setShou_data(data.getHand_str());
			dataFormServer.setXywy_userid(userID);
			bloodServers.add(dataFormServer);
		}
		return gson.toJson(bloodServers);
	}

	BloodPressureData blood_data;

	private DevicesObserver observer;

	Handler observerHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case ObserverConstants.LOGIN_MAKER:
				System.out.println("现在开始获取网络数据-----");
				syncDataFormServer();
				break;
			case ObserverConstants.CHANGE_BLOOD_MAKER:
				setChange();
				break;
			default:
				break;
			}
		};
	};

	private void setChange() {
		List<BloodPressureData> temp = getLastData();
		if (temp != null && temp.size() > 0) {
			BloodPressureData data = temp.get(0);
			tv_last_day.setText(data.getHighPressure() + "/"
					+ data.getLowPressure() + "  "
					+ getDiffTime(data.getDate()));
		} else {
			// tv_last_day.setText("暂无数据");
		}
		setSelectHr(current);
		switch (current) {
		case BloodZxView.MODE_DAY:
			blood_pressure_chart.setGaveWorth(getDayAgoData(), current);
			break;
		case BloodZxView.MODE_MOUNTH:
			blood_pressure_chart.setGaveWorth(getMonthAgoData(), current);
			break;
		case BloodZxView.MODE_WEEK:
			blood_pressure_chart.setGaveWorth(getWeekAgoData(), current);
			break;
		case BloodZxView.MODE_YEAR:
			blood_pressure_chart.setGaveWorth(getYearAgoData(), current);
			break;

		default:
			break;
		}
	}

	void registerDBobserver() {
		observer = new DevicesObserver(observerHandler);
		getActivity().getContentResolver().registerContentObserver(
				ObserverConstants.LOGIN_SUCCESS, false, observer);
	}

	public static final long YEAR = 365;
	public static final long MONTH = 30;
	public static final long DAY = 24;
	public static final long HOUR = 60;
	public static final long MINUTE = 60;
	public static final long SECOND = 1000;
	static long timeFormate[] = new long[6];
	static String timeFormateStr[] = { "年前", "个月前", "天前", "小时前", "分钟前", "秒前" };

	public static String getDiffTime(long dataTime) {
		long currentTime = System.currentTimeMillis();
		long diff = currentTime - dataTime;
		timeFormate[0] = diff / (YEAR * MONTH * DAY * HOUR * MINUTE * SECOND);
		timeFormate[1] = diff / (MONTH * DAY * HOUR * MINUTE * SECOND);
		timeFormate[2] = diff / (DAY * HOUR * MINUTE * SECOND);
		timeFormate[3] = diff / (HOUR * MINUTE * SECOND);
		timeFormate[4] = diff / (MINUTE * SECOND);
		timeFormate[5] = diff / (SECOND);
		int i = 0;
		for (; i < timeFormate.length; i++) {
			if (timeFormate[i] != 0)
				break;
		}
		if (i >= 5) {
			return "刚刚";
		}
		return timeFormate[i] + timeFormateStr[i];
	}
}
